import json

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
import logging
logger = logging.getLogger('log')


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 接收这个客户端的连接
        self.accept()
        print('1111111', message)
        # 将这个客户端的连接对象加入到某个地方（内存 or redis）1314 是群号这里写死了
        # async_to_sync(self.channel_layer.group_add)('1314', self.channel_name)

    def websocket_receive(self, message):
        # 通知组内的所有客户端，执行 xx_oo 方法，在此方法中自己可以去定义任意的功能。
        logger.info('websocket_receive:{}'.format(message))
        data = json.loads(message.get('text', '{}'))
        chat_type = data.get('chat_type')
        chat_id = data.get('chat_id')
        chat_content = data.get('message')
        # 创建聊天群组
        # print('aaaaaaaaaaaa', chat_type)
        if chat_type == 'add_chat':
            async_to_sync(self.channel_layer.group_add)(chat_id, self.channel_name)
        else:
            async_to_sync(self.channel_layer.group_send)(chat_id, {"type": "chat.message", 'message': message})

    def chat_message(self, event):
        text = event['message']['text']
        self.send(text)

    def websocket_disconnect(self, message):
        print('3333333', message)
        if 'text' in message:
            # 断开链接要将这个对象从 channel_layer 中移除
            data = json.loads(message['text'])
            chat_id = data.get('chat_id')
            async_to_sync(self.channel_layer.group_discard)(chat_id, self.channel_name)
            raise StopConsumer()
